package com.mzmarket.market.app.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mzmarket.market.app.domain.*;
import com.mzmarket.market.module.entity.Category;
import com.mzmarket.market.module.entity.Product;
import com.mzmarket.market.module.entity.User;
import com.mzmarket.market.module.service.CategoryService;
import com.mzmarket.market.module.service.ProductService;
import com.mzmarket.market.module.service.UserService;
import com.mzmarket.market.module.utils.JwtCookieUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Slf4j
@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private UserService userService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/product/detail")
    public ProductDetailVO productInfo(@RequestParam(name = "id", required = false) Long id,
                                       HttpServletRequest request) throws IOException {
        /*判断http header中的sign是否符合要求*/
        // 这里可以校验 JWT 签名、过期时间，或者去数据库查 session
        String sign = request.getHeader("Sign");

        ObjectMapper objectMapper = new ObjectMapper();
        ValueInfo valueInfo = objectMapper.readValue(Base64.getDecoder().decode(sign), ValueInfo.class);
        Claims claims = JwtCookieUtil.decrypt(valueInfo.getToken());
        String phone = claims.getSubject();

        User user = null;
        try {
            user = userService.getByPhone(phone);//确认存入用户信息是否准确
        } catch (Exception e) {
            return new ProductDetailVO();
        }
        if (user == null) {
            return new ProductDetailVO();
        } else {
            Date expireDate = claims.getExpiration();//确认sign是否过期
            int result = new Date(System.currentTimeMillis()).compareTo(expireDate);
            if(result > 0){
                return new ProductDetailVO();
            };
        }

        Product product = null;
        try {
            product = productService.getById(id);
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        if (product != null) {
            Category category = null;
            try {
                category = categoryService.getById(product.getCategoryId());
            } catch (Exception e) {
                log.warn(e.getMessage());
            }
            if (category != null) {
                return new ProductDetailVO()
                        .setDescription(product.getDescription())
                        .setPrice(product.getPrice())
                        .setSaleNum(product.getSaleNum())
                        .setImages(Arrays.asList(product.getImages().split("&")))
                        .setTitle(product.getTitle())
                        .setCategoryImage(category.getImage())
                        .setCategoryName(category.getName());
            } else {
                log.warn("Category not found");//脏数据不展示
                return new ProductDetailVO();
            }
        } else {
            return new ProductDetailVO();
        }
    }

    @RequestMapping("/product/list")
    public ProductListVO productAll(@RequestParam(name = "page", required = false) Long page,
                                    @RequestParam(name = "keyword", required = false) String keyword) {
        int pageSize = 3;

        List<ProductCellVO> productListVO = new ArrayList<>();
        List<Product> productList = null;
        try {
            productList = productService.getPageList(pageSize, page, keyword, "app");
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        if (productList != null) {
            for (Product product : productList) {
                Category category = null;
                try {
                    category = categoryService.getById(product.getCategoryId());
                } catch (Exception e) {
                    log.warn("Category get failed");
                    return new ProductListVO();
                }
                if (category == null) {
                    log.warn("Category not found");//存在脏数据不加入列表
                } else {
                    productListVO.add(new ProductCellVO()
                            .setId(product.getId())
                            .setPrice(product.getPrice())
                            .setTitle(product.getTitle())
                            .setImage(product.getImages().split("&")[0])
                            .setFavoriteNum(product.getSaleNum())
                            .setCategoryName(category.getName()));
                }
            }
            return new ProductListVO()
                    .setList(productListVO)
                    .setIsEnd(productList.size() < pageSize);
        } else {
            return new ProductListVO();
        }
    }

}

